package com.example.demo.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.FileItem;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@Service
public class AlipayServiceImpl {
    @Autowired
    private DefaultAlipayClient alipayClient;
    HashMap<String,String> map = new HashMap<>();
    String template_id = null;  //会员卡模板id

    /**
     * 上传logo和背景图
     * @return
     * @throws AlipayApiException
     */
    public HashMap<String,String> imgurlbj() throws AlipayApiException {
        AlipayOfflineMaterialImageUploadRequest request = new AlipayOfflineMaterialImageUploadRequest();
        request.setImageType("png");
        request.setImageName("畅易租商户会员卡");
        String classesPath=Thread.currentThread().getContextClassLoader().getResource("").getPath().substring(1);
        FileItem ImageContent = new FileItem(classesPath+"\\logo.png");
        System.err.println("user.dir:=="+classesPath);
        request.setImageContent(ImageContent);
        UUID uuid = UUID.randomUUID();
        String uuid1=String.valueOf(uuid);
        request.setImagePid(uuid1);
        AlipayOfflineMaterialImageUploadResponse response = alipayClient.execute(request);
        String AlipayResultS = response.getBody();
        JSONObject AlipayResult = JSONObject.parseObject(AlipayResultS);
        if (AlipayResult != null) {
            JSONObject AlipayJson = AlipayResult.getJSONObject("alipay_offline_material_image_upload_response");
            try {
                String msg = AlipayJson.getString("msg");
                String image_id = AlipayJson.getString("image_id");
                String image_url = AlipayJson.getString("image_url");
                map.put("msg",msg);
                map.put("image_id",image_id);
                map.put("image_url",image_url);
            } catch (Exception e) {
                e.getMessage();
            }

        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return map;
    }

    /**
     * 创建会员卡模板
     * @return
     * @throws AlipayApiException
     */
    public HashMap<String,String> model() throws AlipayApiException {
        AlipayMarketingCardTemplateCreateRequest request = new AlipayMarketingCardTemplateCreateRequest();
        String appAuthToken = null;
        String format1="";
        String finnalyStatus="";
        long time = new Date().getTime();
        System.out.println(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String format = sdf.format(date);
        format1 = format;
        String leixing = "OUT_MEMBER_CARD";
        String card="prex";
        String sfzh = "431382199908100065";


        String bizContent="{\n" +
                "    \"request_id\": \""+time+"\",\n" +
                "    \"card_type\": \"OUT_MEMBER_CARD\",\n" +
                "    \"biz_no_prefix\": \"prexupdate\",\n" +
                "    \"biz_no_suffix_len\": \"15\",\n" +/*业务卡号后缀的长度*/
                "    \"write_off_type\": \"none\",\n" +
                "    \"template_style_info\": {\n" +
                "        \"card_show_name\": \"畅易租商户会员卡\",\n" +
                "        \"logo_id\": \"sIN8vIegS5eHwZn6p9ir0QAAACMAAQQD\",\n" +
                "        \"color\": \"rgb(55,112,179)\",\n" +
                "        \"background_id\": \"MVBIpZLbSxy8Ye28U79ARAAAACMAAQQD\",\n" +
                "        \"bg_color\": \"rgb(55,112,179)\"\n" +
                "    },\n" +
                "    \"column_info_list\": [{\n" +
                "        \"code\": \"BENEFIT_INFO\",\n" +
                "        \"more_info\":{\n" +
                "        \"title\": \"扩展信息\",\n" +
                "        \"url\": \"alipays://platformapi/startapp?appId=2021001164604451&page=pages/activate/index&query="+sfzh+"\",\n" +
                "        \"params\": \"{}\"\n" +
                "    },\n" +
                "        \"title\": \"卡号\",\n" +
                "        \"operate_type\": \"openWeb\",\n" +
                "        \"value\": \""+card+"\"\n" +
                "    }, {\n" +
                "        \"code\": \"NAME\",\n" +
                "        \"title\": \"姓名\",\n" +
                "        \"value\": \""+"张三"+"\"\n" +
                "    }, {\n" +
                "        \"code\": \"SFZH\",\n" +
                "        \"title\": \"有效日期\",\n" +
                "        \"value\": \""+format1+"\"\n" +
                "    }, {\n" +
                "        \"code\": \"TYPE\",\n" +
                "        \"title\": \"类型\",\n" +
                "        \"value\": \""+leixing+"卡\"\n" +
                "    }],\n" +
                "    \"field_rule_list\": [{\n" +
                "        \"field_name\": \"Balance\",\n" +
                "        \"rule_name\": \"ASSIGN_FROM_REQUEST\",\n" +
                "        \"rule_value\": \"Balance\"\n" +
                "    }]\n" +
                "}";
        request.putOtherTextParam("app_auth_token", appAuthToken);
        request.setBizContent(bizContent);
        AlipayMarketingCardTemplateCreateResponse response = alipayClient.execute(request);

        String body = response.getBody();
        if(response.isSuccess()) {
            System.err.println("调用成功");
            System.err.print("response.getBody():=="+response.getBody());//根据业务处理response
            String AlipayResultS = response.getBody();
            JSONObject AlipayResult = JSONObject.parseObject(AlipayResultS);
            if (AlipayResult != null) {
                JSONObject AlipayJson = AlipayResult.getJSONObject("alipay_marketing_card_template_create_response");
                try {
                    template_id = AlipayJson.getString("template_id");
                    String msg = AlipayJson.getString("msg");
                    map.put("msg",msg);
                    map.put("template_id",template_id);
                } catch (Exception e) {
                    finnalyStatus = "认证已失效，请重试";
                }
            }
        }

        return map;
    }

    /**
     * 会员卡开卡表单模板配置
     * @param //template_id
     * @return
     * @throws AlipayApiException
     */
    public String chuangjian() throws AlipayApiException{
        AlipayMarketingCardFormtemplateSetRequest request = new AlipayMarketingCardFormtemplateSetRequest();
        String bizContent="{\n" +
                "\"template_id\":\""+template_id+"\"," +
                "\"fields\":{" +
                "\"required\":\"{\\\"common_fields\\\":[\\\"OPEN_FORM_FIELD_MOBILE\\\"]}\"" +
                "}" +
                "}";
        request.setBizContent(bizContent);
        AlipayMarketingCardFormtemplateSetResponse response = alipayClient.execute(request);
        return response.getBody();
    }
    /**
     * 获取会员卡领卡投放链接
     * @param //template_id
     * @return
     * @throws AlipayApiException
     */
    public HashMap<String,String> fafang() throws AlipayApiException {
        AlipayMarketingCardActivateurlApplyRequest request = new AlipayMarketingCardActivateurlApplyRequest();
        UUID uuid = UUID.randomUUID();
        String uuid1=String.valueOf(uuid);
        System.out.println("uuid:"+uuid1);
        String bizContent="{\n" +
                "  \"template_id\": \""+template_id+"\",\n" +
                "  \"out_string\": \"201928393932\"\n" +
                "}";
        request.setBizContent(bizContent);
        AlipayMarketingCardActivateurlApplyResponse response = alipayClient.execute(request);
        String AlipayResultS = response.getBody();
        JSONObject AlipayResult = JSONObject.parseObject(AlipayResultS);
        if (AlipayResult != null) {
            JSONObject AlipayJson = AlipayResult.getJSONObject("alipay_marketing_card_activateurl_apply_response");
            try {
                String apply_card_url = AlipayJson.getString("apply_card_url");
                String msg = AlipayJson.getString("msg");
                map.put("msg",msg);
                map.put("apply_card_url",apply_card_url);
                System.out.println(apply_card_url);
            } catch (Exception e) {
                e.getMessage();
            }

        }
        return map;
    }
    /**
     * 根据 code获取AccessToken 和UserId
     * @param code
     * @return
     */
    public HashMap<String, String> urlsgrz(String code) {
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(code);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            System.out.println("AccessToken:" + oauthTokenResponse.getAccessToken());
            System.err.println("user_id:" + oauthTokenResponse.getUserId());
            if (oauthTokenResponse.getAccessToken() == null && oauthTokenResponse.getUserId() == null) {
                map.put("success", "false");
                map.put("message:", "参数code无效");
            } else {
                map.put("success", "true");
                map.put("AccessToken", oauthTokenResponse.getAccessToken());
                map.put("UserId", oauthTokenResponse.getUserId());
            }
//            map.put("AccessToken",oauthTokenResponse.getAccessToken());
//            map.put("UserId",oauthTokenResponse.getUserId());
        } catch (AlipayApiException e) {
            //处理异常
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 查询用户提交的会员卡表单信息
     * @param template_id
     * @param accessToken
     * @param requestId
     * @return
     * @throws AlipayApiException
     */
    public HashMap<String, String> userInfo(String template_id,String accessToken,String requestId) throws AlipayApiException {
        AlipayMarketingCardActivateformQueryRequest request = new AlipayMarketingCardActivateformQueryRequest();
        UUID uuid = UUID.randomUUID();
        String uuid1 = String.valueOf(uuid);
        String bizContent = "{\n" +
                "  \"biz_type\": \"MEMBER_CARD\",\n" +
                "  \"template_id\": \"" + template_id + "\",\n" +
                "  \"request_id\": \"" + requestId + "\"\n" +
                "}";
        request.setBizContent(bizContent);
        AlipayMarketingCardActivateformQueryResponse response = alipayClient.execute(request, accessToken);
        String AlipayResultS = response.getBody();
        JSONObject AlipayResult = JSONObject.parseObject(AlipayResultS);
        if (AlipayResult != null) {
            JSONObject AlipayJson = AlipayResult.getJSONObject("alipay_marketing_card_activateform_query_response");
            try {
                String msg = AlipayJson.getString("msg");
                String code = AlipayJson.getString("code");
                String infos = AlipayJson.getString("infos");
                map.put("msg",msg);
                map.put("code",code);
                map.put("infos",infos);
            } catch (Exception e) {
                e.getMessage();
            }

        }
        return map;
    }
    /**
     * 会员卡开卡
     * @param template_id
     * @param accessToken
     * @param UserId
     * @return
     * @throws AlipayApiException
     */
    public HashMap<String, String> opencard(String template_id,String accessToken,String UserId) throws AlipayApiException {
        AlipayMarketingCardOpenRequest request = new AlipayMarketingCardOpenRequest();
        String format1="";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long time = new Date().getTime();
        Date date = new Date();
        String format = sdf.format(date);
        format1 = format;
        System.out.println("format"+format+"，format1"+format1);
        String LianXiRen="";
        LianXiRen= "畅易租";
        String xingbie="";
        xingbie="FEMALE";
        String shengri="";
        shengri="";
        String lianXiDianHua = "";
        UUID uuid = UUID.randomUUID();
        UUID uuid2 = UUID.randomUUID();
        String uuid1=String.valueOf(uuid);
        String uuid3=String.valueOf(uuid2);
        request.setBizContent("{" +
                "\"out_serial_no\":\""+uuid1+"\"," +
                "\"card_template_id\":\""+template_id+"\"," +
                "\"card_user_info\":{" +
                "\"user_uni_id\":\""+UserId+"\"," +
                "\"user_uni_id_type\":\"UID\"" +
                "    }," +
                "\"card_ext_info\":{" +
                "\"biz_card_no\":\""+uuid3+"\"," +
                "\"external_card_no\":\"畅易租商户会员卡\"," +
                "\"open_date\":\""+format+"\"," +
                "\"valid_date\":\"2021-06-02 10:57:35\"," +
                "\"level\":\"VIP1\"," +
                "\"point\":\"88\"," +
                "\"balance\":\"124.89\"," +/*资金卡余额，单位：元，精确到小数点后两位。*/
                "\"mdcode_info\":{" +
                "\"code_status\":\"SUCCESS\"," +
                "\"code_value\":\"1KFCDY0002\"," +
                "\"expire_time\":\"2021-05-30 16:25:53\"," +
                "\"time_stamp\":"+time+"" +
                "      }," +
                "        \"front_text_list\":[{" +
                "          \"label\":\"专业\"," +
                "\"value\":\"金融贸易\"" +
                "          }]," +
                "\"front_image_id\":\"9fxnkgt0QFmqKAl5V2BqxQAAACMAAQED\"" +
                "    }," +
                "\"member_ext_info\":{" +
                "\"name\":\""+LianXiRen+"\"," +
                "\"gende\":\""+xingbie+"\"," +
                "\"birth\":\""+shengri+"\"," +
                "\"cell\":\""+lianXiDianHua+"\"" +
                "    }," +
                "\"open_card_channel\":\"20161534000000000008863\"," +
                "\"open_card_channel_id\":\"2088123123123123\"" +
                "  }");
        request.putOtherTextParam("app_auth_token", null);
        AlipayMarketingCardOpenResponse response = alipayClient.execute(request,accessToken);
        String AlipayResultS = response.getBody();
        JSONObject AlipayResult = JSONObject.parseObject(AlipayResultS);
        if (AlipayResult != null) {
            JSONObject AlipayJson = AlipayResult.getJSONObject("alipay_marketing_card_open_response");
            try {
                String msg = AlipayJson.getString("msg");
                String code = AlipayJson.getString("code");
                String card_info = AlipayJson.getString("card_info");
                map.put("msg",msg);
                map.put("code",code);
                map.put("card_info",card_info);
            } catch (Exception e) {
                e.getMessage();
            }
        }
        return map;
    }
    /**
     * 会员卡查询接口
     * @return
     * @throws AlipayApiException
     */
    public HashMap<String,String> query() throws AlipayApiException {
        AlipayMarketingCardQueryRequest request = new AlipayMarketingCardQueryRequest();
        request.setBizContent("{" +
                "\"target_card_no_type\":\"BIZ_CARD\"," +
                "\"target_card_no\":\"0000001\"," +
                "\"card_user_info\":{" +
                "\"user_uni_id\":\"2088302463082075\"," +
                "\"user_uni_id_type\":\"UID\"" +
                "    }," +
                "\"ext_info\":\"\\\"\\\"\"" +
                "  }");
        AlipayMarketingCardQueryResponse response = alipayClient.execute(request);
        String AlipayResultS = response.getBody();
        JSONObject AlipayResult = JSONObject.parseObject(AlipayResultS);
        if (AlipayResult != null) {
            JSONObject AlipayJson = AlipayResult.getJSONObject("alipay_marketing_card_query_response");
            try {
            } catch (Exception e) {
                e.getMessage();
            }
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        return map;
    }

    /**
     * 更新会员卡模板
     * @return
     * @throws AlipayApiException
     */
    public HashMap<String,String> update(String template_id) throws AlipayApiException {
        AlipayMarketingCardUpdateRequest request = new AlipayMarketingCardUpdateRequest();
        request.setBizContent("{" +
                "\"target_card_no\":\"000001\"," +
                "\"target_card_no_type\":\"BIZ_CARD\"," +
                "\"occur_time\":\"2016-06-27 12:12:12\"," +
                "\"card_info\":{" +
                "\"open_date\":\"2014-02-20 21:20:46\"," +
                "\"valid_date\":\"2020-02-20 21:20:46\"," +
                "\"level\":\"VIP1\"," +
                "\"point\":\"88\"," +
                "\"balance\":\"124.89\"," +
                "\"template_id\":\""+template_id+"\"," +
                "\"mdcode_info\":{" +
                "\"code_status\":\"SUCCESS\"," +
                "\"code_value\":\"1KFCDY0002\"," +
                "\"expire_time\":\"2017-06-09 16:25:53\"," +
                "\"time_stamp\":1496996459" +
                "      }," +
                "        \"front_text_list\":[{" +
                "          \"label\":\"专业\"," +
                "\"value\":\"金融贸易\"" +
                "          }]," +
                "\"front_image_id\":\"9fxnkgt0QFmqKAl5V2BqxQAAACMAAQED\"" +
                "    }," +
                "\"ext_info\":\"\\\"\\\"\"," +
                "      \"notify_messages\":[{" +
                "        \"message_type\":\"OPEN_CARD\"," +
                "\"change_reason\":\"由于你的消费\"," +
                "\"ext_info\":\"{}\"" +
                "        }]," +
                "\"mcard_style_info\":{" +
                "\"bg_color\":\"rgb(55,112,179)\"," +
                "\"logo_id\":\"MVBIpZLbSxy8Ye28U79ARAAAACMAAQQD\"," +
                "\"background_id\":\"sIN8vIegS5eHwZn6p9ir0QAAACMAAQQD\"" +
                "    }" +
                "  }");
        AlipayMarketingCardUpdateResponse response = alipayClient.execute(request);
        String AlipayResultS = response.getBody();
        JSONObject AlipayResult = JSONObject.parseObject(AlipayResultS);
        if (AlipayResult != null) {
            JSONObject AlipayJson = AlipayResult.getJSONObject("alipay_marketing_card_update_response");
            String msg = AlipayJson.getString("msg");
            String code = AlipayJson.getString("code");
            String result_code = AlipayJson.getString("result_code");
            map.put("msg",msg);
            map.put("code",code);
            map.put("result_code",result_code);
            try {
            } catch (Exception e) {
                e.getMessage();
            }
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return map;
    }

    /**
     * 会员卡删卡
     * @return
     * @throws AlipayApiException
     */
    public HashMap<String,String> delete() throws AlipayApiException {
        AlipayMarketingCardDeleteRequest request = new AlipayMarketingCardDeleteRequest();
        request.setBizContent("{" +
                "\"out_serial_no\":\"2016062700001\"," +
                "\"target_card_no\":\"0000001\"," +
                "\"target_card_no_type\":\"BIZ_CARD\"," +
                "\"reason_code\":\"USER_UNBUND\"," +
                "\"ext_info\":\"{\\\"new_card_no\\\":\\\"12345\\\",\\\" donee_user_id\\\":\\\"2088102130652460\\\"}\"" +
                "  }");
        AlipayMarketingCardDeleteResponse response = alipayClient.execute(request);
        String AlipayResultS = response.getBody();
        JSONObject AlipayResult = JSONObject.parseObject(AlipayResultS);
        if (AlipayResult != null) {
            JSONObject AlipayJson = AlipayResult.getJSONObject("alipay_marketing_card_update_response");
            String msg = AlipayJson.getString("msg");
            String code = AlipayJson.getString("code");
            String biz_serial_no = AlipayJson.getString("biz_serial_no");
            map.put("msg",msg);
            map.put("code",code);
            map.put("biz_serial_no",biz_serial_no);
            try {
            } catch (Exception e) {
                e.getMessage();
            }
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return map;
    }

    /**
     * 会员卡修改模板
     * @return
     */
    public HashMap<String,String> modify(String template_id) throws AlipayApiException {
        AlipayMarketingCardTemplateQueryRequest request = new AlipayMarketingCardTemplateQueryRequest();
        request.setBizContent("{" +
                "\"template_id\":\""+template_id+"\"" +
                "  }");
        AlipayMarketingCardTemplateQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return map;
    }

    /**
     * 会员卡模板查询接口
     * @return
     * @throws AlipayApiException
     */
    public HashMap<String,String> templatequery(String template_id) throws AlipayApiException {
        AlipayMarketingCardTemplateQueryRequest request = new AlipayMarketingCardTemplateQueryRequest();
        request.setBizContent("{" +
                "\"template_id\":\""+template_id+"\"" +
                "  }");
        AlipayMarketingCardTemplateQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return map;
    }
}
